@extends('common.admin_template')

@section('content')
    <div class="boxWidth">
        @include('common.notice_msg')
        <form id="service" method="post" action="{{url('admin/shops/save')}}">
            <input type="hidden" name="_token" value="{{ csrf_token() }}">
            <input type="hidden" name="Post[id]" id="id" value="{{ isset($Post)?$Post->id:"" }}">
            <input type="hidden" name="Post[content]" id="PostContent">
            <div class="row">
                <div class="col-xs-9 boxPaddingLeft">
                    <div class="row editFormItem">
                        <div class="col-xs-1 postItemName"><span>名称</span><i class="glyphicon icon-arrow-left"></i></div>
                        <div class="col-xs-11" id="titleNameBox"><input type="text" class="form-control" id="titleName" name="Post[name]" placeholder="请输入店铺名称" value="{{ isset($Post)?$Post->name:'' }}"></div>
                    </div>
                    <div class="row editFormItem">
                        <div class="col-xs-1 postItemName"><span>封面</span></div>
                        <div class="col-xs-10" id="coverNameBox"><input type="text" class="form-control" id="coverName" name="Post[cover]" placeholder="请输入图片链接或点击右边按钮上传封面图片" value="{{ isset($Post)?$Post->cover:'' }}"></div>
                        <div class="col-xs-1" id="coverImg"><img src="{{asset('img/upload.png')}}" alt=""></div>
                    </div>
                    <div class="row editFormItem">
                        <div class="col-xs-1 postItemName"><span>概要</span></div>
                        <div class="col-xs-11"><input type="text" class="form-control" id="summaryName" name="Post[summary]" placeholder="请输入店铺顶部文字，例如服务宗旨或最新活动等" value="{{ isset($Post)?$Post->summary:'' }}"></div>
                    </div>
                    <div class="row editFormItem">
                        <div class="col-xs-1 postItemName"><span>地址</span></div>
                        <div class="col-xs-11" id="addressNameBox"><input type="text" class="form-control" id="addressName" name="Post[address]" placeholder="请输入店铺地址" value="{{ isset($Post)?$Post->address:''}}"></div>
                    </div>
                    <div class="row editFormItem">
                        <div class="col-xs-1 postItemName"><span>管理者</span></div>
                        <div class="col-xs-11"><input type="text" class="form-control" id="user_id" name="Post[user_id]" placeholder="请输入店铺管理者的ID，如不填默认为管理员" value="{{isset($Post)?$Post->user_id:'' }}"></div>
                    </div>
                    <div class="row editFormItem">
                        <div class="col-xs-1 postItemName"><span>优惠限制</span></div>
                        <div class="col-xs-11 postItemName"><input style="width: 20px;margin: -4px 0 0;float: left;" type="checkbox" name="Post[coupon_use_limit]" {{ isset($meta)&&isset($meta["coupon_use_limit"])?'checked':'' }}><div style="float: left;padding-left: 10px;">只允许商铺优惠券，不能使用全场券</div></div>
                    </div>
                    <div class="row editFormItem">
                        <div class="col-xs-1 postItemName"><span>二维码</span></div>
                        <div class="col-xs-10" ><input type="text" class="form-control" name="Post[viewQR]" placeholder="小程序分享二维码，勾选右边按钮自动生成" value="{{ isset($meta)&&isset($meta["viewQR"])?$meta["viewQR"]:'' }}"></div>
                        <div class="col-xs-1 postItemName qrCreate"><input type="checkbox" name="Post[createQR]"></div>
                    </div>
                    <div class="row editFormItem">
                        <div class="col-xs-12">
                            <div class="postBox" contenteditable="true" id="PostContentBox">
                                {!! isset($Post)?$Post->content:''  !!}
                            </div>
                        </div>
                    </div>
                    <div id="postItemValueContainer">
                        <div class="row editFormItem">
                            <div class="col-xs-2 postItemName">
                                {{--<span>服务说明</span>--}}
                            </div>
                            <div class="col-xs-6 activeItemBtn">
                                {{--<span id="activeChange" style="display: block"><span class="redColor" id="delActive">删除</span><span id="addActive">添加</span></span>--}}
                            </div>
                            <div class="col-xs-4" id="contentImg"><button><img src="{{asset('img/upload.png')}}">上传图片</button></div>
                        </div>
                        {{--<div class="row editFormItem" id="postItemValueBox">--}}
                            {{--<div class="col-xs-2 postItemName"></div>--}}
                            {{--<div class="row col-xs-10 postItemValue" id="postItemValue">--}}
                                {{--<div class="row"><div class="col-xs-6">名称</div><div class="col-xs-6">值</div></div>--}}
                                {{--<div class="row">--}}
                                    {{--<div class="col-xs-6" id="activeKey_0Box"><input type="text" id="activeKey_0" class="form-control" name="Post[activeKey_0]" value=""></div>--}}
                                    {{--<div class="col-xs-6" id="activeValue_0Box"><input type="text" id="activeValue_0" class="form-control" name="Post[activeValue_0]" value=""></div>--}}
                                {{--</div>--}}
                            {{--</div>--}}
                        {{--</div>--}}
                    </div>
                    <div class="row editFormItem">
                        <div class="col-xs-2 postItemName"><span>经营时间</span></div>
                        <div class="row col-xs-10 postItemValue">
                            <div class="row"><div class="col-xs-6">开始时间</div><div class="col-xs-6">结束时间</div></div>
                            <div class="row">
                                <div class="col-xs-6"><input type="text" id="startService" readonly class="form-control form_datetime" name="Post[startService]" value=""></div>
                                <div class="col-xs-6"><input type="text" id="endService" readonly class="form-control form_datetime" name="Post[endService]" value=""></div>
                            </div>
                        </div>
                    </div>
                    <div class="row editFormItem">
                        <div class="col-xs-2 postItemName"><span>服务电话</span></div>
                        <div class="col-xs-10 activeItemBtn" id="phoneBox"><input type="text" class="form-control" id="phone" name="Post[phone]" placeholder="请输入服务手机号" value="{{ isset($Post)?$Post->phone:'' }}">
                        </div>
                    </div>
                    <div class="row editFormItem">
                        <div class="col-xs-2 postItemName"><span>配送费</span></div>
                        <div class="col-xs-10 activeItemBtn"><input type="text" class="form-control" name="Post[delivery]" placeholder="请输入配送费" value="{{ isset($meta)&&isset($meta["delivery"])?$meta["delivery"]:'0' }}">
                        </div>
                    </div>
                    <div class="row editFormItem">
                        <div class="col-xs-2 postItemName"><span>满减活动(选填)</span></div>
                        <div class="row col-xs-10 postItemValue">
                            <div class="row">
                                <div class="col-xs-6"><input type="text" class="form-control" placeholder="请输入需要达到金额" name="Post[discount_full]" value="{{ isset($meta)&&isset($meta["discount_full"])?$meta["discount_full"]:'' }}"></div>
                                <div class="col-xs-6"><input type="text" class="form-control" placeholder="请输入优惠减去金额" name="Post[discount_cut]" value="{{ isset($meta)&&isset($meta["discount_cut"])?$meta["discount_cut"]:'' }}"></div>
                            </div>
                        </div>
                    </div>
                    <div class="row editFormItem">
                        <div class="col-xs-2 postItemName"><span>近期活动(选填)</span></div>
                        <div class="col-xs-10 activeItemBtn"><input type="text" class="form-control" name="Post[active]" placeholder="请输入活动简要说明或需要突出的优惠" value="{{ isset($meta)&&isset($meta["active"])?$meta["active"]:'' }}">
                        </div>
                    </div>
                </div>
                <div class="col-xs-3 boxPaddingRight">
                    <div class="postBtnBox">
                        <div class="row postItem">
                            <div class="col-xs-3 postItemName"><span>状态</span></div>
                            <div class="col-xs-8">
                                <select name="Post[status]" id="postStatus">
                                    <option value="0">待审</option>
                                    <option value="1">通过</option>
                                </select>
                            </div>
                        </div>
                        {{--<div class="row postItem">--}}
                            {{--<div class="col-xs-3 postItemName"><span>等级</span></div>--}}
                            {{--<div class="col-xs-8">--}}
                                {{--<select name="Post[level]" id="postLevel">--}}
                                    {{--<option value="0">普通</option>--}}
                                    {{--<option value="1">置顶</option>--}}
                                    {{--<option value="2">幻灯片</option>--}}
                                {{--</select>--}}
                            {{--</div>--}}
                        {{--</div>--}}
                        @if(isset($Post))
                            <div class="row postItem">
                                <div class="col-xs-3 postItemName"><span>创建时间</span></div>
                                <div class="col-xs-8"><input type="text" id="created_at" readonly name="Post[created_at]" value="">
                                </div>
                            </div>
                        @endif
                        <div class="row postItemBtn" >
                            <div class="col-xs-8"><button class="btn btn-primary" type="submit" id="formSubmit">发布</button></div>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
@stop
@section('js')
    <script src="{{asset('js/bootstrap-datetimepicker.js')}}"></script>
    <script src="{{asset('js/plupload/plupload.full.min.js')}}"></script>
    <script src="{{asset('js/quill.js')}}"></script>
    <script>
        (function () {
            function getId(arr,num) {
                return arr.indexOf(Number(num));
            }
            function hasError(id){
                var str =  $('#'+id).val().replace(/(^\s*)|(\s*$)/g, "");
                if(!str){
                    $('#'+id+'Box').addClass('has-error');
                    return 1;
                }
                return 0;
            }
            function activeChange(value) {
                if(value!='no'){
                    $('#activeChange').show();
                    if(value==0){
                        $('#postItemValue').append(
                                '<div class="row">' +
                                '<div class="col-xs-6" id="activeKey_0Box"><input type="text" id="activeKey_0" class="form-control" name="Post[activeKey_0]"></div>' +
                                '<div class="col-xs-6" id="activeValue_0Box"><input type="text" id="activeValue_0" class="form-control" name="Post[activeValue_0]"></div>' +
                                '</div>');
                    }else if(value=="edit"){
                                @if(isset($meta)&&isset($meta["service"]))
                        {!!'var activeArr = '.$meta["service"]!!}
                        var arr="";
                        for(var k = 0;k<activeArr.key.length;k++){
                            arr +=  '<div class="row">' +
                                    '<div class="col-xs-6" id="activeKey_'+k+'Box"><input type="text" id="activeKey_'+k+'" class="form-control" name="Post[activeKey_'+k+']" value="'+activeArr.key[k]+'"></div>' +
                                    '<div class="col-xs-6" id="activeValue_'+k+'Box"><input type="text" id="activeValue_'+k+'" class="form-control" name="Post[activeValue_'+k+']" value="'+activeArr.value[k]+'"></div>' +
                                    '</div>';
                        }
                        $('#postItemValue').append(arr);
                        @endif
                    }else{
                        var idx = getId(formId,value);
                        if(idx != -1){
                            for(var i=0;i<formArr[idx].item.length;i++){
                                var num = $('#postItemValue .row').length - 1;
                                $('#postItemValue').append(
                                        '<div class="row">' +
                                        '<div class="col-xs-6" id="activeKey_'+num+'Box"><input type="text" id="activeKey_'+num+'" class="form-control" name="Post[activeKey_'+num+']" value="'+formArr[idx].item[i]+'"></div>' +
                                        '<div class="col-xs-6" id="activeValue_'+num+'Box"><input type="text" id="activeValue_'+num+'" class="form-control" name="Post[activeValue_'+num+']"></div>' +
                                        '</div>');

                            }
                        }
                    }
                }else{
                    $('#activeChange').hide();
                }
            }
            function getToken() {
                $.ajax({
                    url: '{{asset("qiniu.php")}}',
                    type: "get",
                    success: function (response) {
                        token = response;
                        if(!tokenTime){
                            uploader.init();
                        }
                        tokenTime = Math.round(new Date().getTime()/1000);
                    },
                    error: function () {
                        alert('加载失败')
                    },
                    complete: function () {}
                });
            }
            function upInit() {
                if(Math.round(new Date().getTime()/1000)>(tokenTime+3500)){getToken()}
            }

            var token,tokenTime;
            var id = function(id) {return document.getElementById(id);};
            var editor = new Quill('#PostContentBox', {
                modules: {
                    toolbar: [
                        [{ header: [1, 2, 3, 4, 5, 6, false] }],
                        ['bold', 'italic', 'underline', 'strike', { 'align': [] }],
                        [{ 'color': [] }, { 'background': [] }],
                        [{ 'indent': '-1'}, { 'indent': '+1' }, { 'list': 'bullet' }]
                    ] },
                theme: 'snow'
            });
            var Align = Quill.import('attributors/style/align');
            Align.whitelist = ['right', 'center', 'justify'];
            Quill.register(Align, true);

            var picName = new Date();
            var upType;
            picName = picName.getFullYear().toString()+((picName.getMonth()+1)<10?'0'+(picName.getMonth()+1):(picName.getMonth()+1))+(picName.getDate()<10?'0'+picName.getDate():picName.getDate().toString())+'_'+(picName.getHours()<10?'0'+picName.getHours():picName.getHours().toString())+(picName.getMinutes()<10?'0'+picName.getMinutes():picName.getMinutes().toString())+(picName.getSeconds()<10?'0'+picName.getSeconds():picName.getSeconds().toString());

            $(".form_datetime").datetimepicker({format: 'hh:ii',startView:1});
            @if(isset($meta)&&isset($meta["startService"]))
                $('#startService').val("{{$meta["startService"]}}");
            @else
                $('#startService').val("09:00");
            @endif
            @if(isset($meta)&&isset($meta["endService"]))
                $('#endService').val("{{$meta["endService"]}}");
            @else
                $('#endService').val("18:00");

            @endif

            $('#activeItem').on('change',function () {
                $('#postItemValueBox').remove();
                activeChange($(this).val());
            });

            $('#addActive').on('click',function () {
                var num = $('#postItemValue .row').length - 1;
                $('#postItemValue').append(
                        '<div class="row">' +
                        '<div class="col-xs-6" id="activeKey_'+num+'Box"><input type="text" id="activeKey_'+num+'" class="form-control" name="Post[activeKey_'+num+']"></div>' +
                        '<div class="col-xs-6" id="activeValue_'+num+'Box"><input type="text" id="activeValue_'+num+'" class="form-control" name="Post[activeValue_'+num+']"></div>' +
                        '</div>'
                );
            });
            $('#delActive').on('click',function () {
                var row = $('#postItemValue .row'),
                        num = row.length-1;
                if(num>0){
                    row[num].remove();
                }else{
                    alert('没有可删除内容')
                }
            });

            $('#addForm').on('click',function () {
                var num = $('#formItemValue .row').length - 1;
                $('#formItemValue').append(
                        '<div class="row">' +
                        '<div class="col-xs-12" id="form_'+num+'Box"><input type="text" id="form_'+num+'" class="form-control" name="Post[form_'+num+']"></div>' +
                        '</div>'
                );
            });
            $('#delForm').on('click',function () {
                var row = $('#formItemValue .row'),
                        num = row.length-1;
                if(num>2){
                    row[num].remove();
                }else{
                    alert('请至少保证两项表单项目')
                }
            });

            $('#formSubmit').on('click',function (e) {
                var sub = 0,
                    i = 0,
                    content = $('.ql-editor').html(),
                    tagGroup = $(".postTagBox input");
                $('#PostContent').val(content);

                if(hasError('titleName'))sub=1;
                if(hasError('addressName'))sub=1;


                if(sub){
                    e.preventDefault();
                }
            });


            $('#coverImg').on('click',function () {
                upType = 'cover';
                upInit()
            });
            $('#contentImg').on('click',function () {
                upType = 'content';
                upInit()
            });

            var uploader = new plupload.Uploader({
                browse_button : ['contentImg','coverImg'],
                runtimes : 'html5,flash,silverlight,html4',
                url : "https://up.qbox.me/",
                flash_swf_url : "{{asset('js/plupload/Moxie.swf')}}",
                silverlight_xap_url : "{{asset('js/plupload/Moxie.xap')}}",
                unique_names : true,
                init: {
                    PostInit: function() {},
                    BeforeUpload:function(up,file){
                        uploader.setOption("multipart_params",{
                            'token': token,
                            'key': picName+ file.id
                        });
                    },
                    FilesAdded: function(up, files) {
                        plupload.each(files, function(file) {
                            if(upType === 'cover'){
                                $('#coverName').val("等待...")
                            }else if(upType === 'video'){
                                $('#videoName').val("等待...")
                            }
                        });
                    },
                    QueueChanged:function(){
                        uploader.start();
                    },
                    UploadProgress: function(up, file) {
                        if(upType === 'cover'){
                            $('#coverName').val(file.percent + "%")
                        }else if(upType === 'video'){
                            $('#videoName').val(file.percent + "%")
                        }
                        if(file.percent==100){
                            if(upType === 'cover'){
                                $('#coverName').val("即将完成")
                            }else if(upType === 'video'){
                                $('#videoName').val("即将完成")
                            }
                        }
                    },
                    FileUploaded:function(up, file, res){
                        if(upType === 'cover'){
                            $('#coverName').val("https://blhd.1demo.com/"+picName+ file.id)
                        }else if(upType === 'content'){
                            $('.ql-editor').append("<img src=\"https://blhd.1demo.com/"+picName+ file.id+"\" />")
                        }else{
                            $('#videoName').val("https://blhd.1demo.com/"+picName+ file.id)
                        }
                    },
                    UploadComplete: function(up, files) {
                        console.log('complete')
                    },
                    Error : function(up, err) {
                        console.log('fail')
                    }
                }
            });
            getToken();

            @if(isset($Post))
            $("#postStatus").val({{$Post->status}});

            $("#created_at").datetimepicker({format: 'yyyy-mm-dd hh:ii:ss'});
            $('#created_at').val("{{$Post->created_at}}");
            @endif



        })();
    </script>
@stop